package com.xiaolei.fastnio.http.Protocol

import com.xiaolei.fastnio.http.Request
import com.xiaolei.fastnio.library.Client.Session
import com.xiaolei.fastnio.library.Protocol.IProtocol
import okio.Buffer
import java.util.concurrent.ConcurrentLinkedQueue

private val idleStore = ConcurrentLinkedQueue<Request>()


/**
 * 对于Http的Request请求缓存的解码器
 * 集成OKio的Buffer
 */
abstract class HttpRequestCacheProtocol : IProtocol<Request>
{
    private var request: Request? = null
    private val buffer = Buffer()
    
    override fun decode(session: Session, byteArray: ByteArray, len: Int): Request?
    {
        buffer.write(byteArray, 0, len)
        if (request == null)
        {
            request = idleStore.poll()
            if (request == null)
            {
                request = Request()
            }
            request!!.session = session
        }
        return decodeRequest(session, buffer, request!!)
    }

    abstract fun decodeRequest(session: Session, buffer: Buffer, request: Request): Request?

    override fun onClear()
    {
        buffer.clear()
        request?.onClear()
        idleStore.offer(request)
        request = null
    }
}